import axios from "axios";
import {createDiscreteApi} from "naive-ui";
import {useTokenStore} from "@/stores/token.js";
import router from "@/router/index.js";
const {message} = createDiscreteApi(
    ["message", 'dialog', 'notification', 'loadingBar', 'modal']
)

export const serverBaseURL = "http://localhost:8080"
export const clientBaseURL = "http://localhost:5173"

const instance = axios.create({
    baseURL: "/api",
})
// const tokenStore = useTokenStore()
instance.interceptors.request.use(
    config=>{
        const tokenStore = useTokenStore()
        if (tokenStore.token){
            config.headers.set("jwt-token", tokenStore.token)
        }

        return config
    },
    err=>{
        Promise.reject(err)
    }
)

instance.interceptors.response.use(
    result=>{
        if (result.data.code === 1){
            return result.data
        }
        message.error(result.data.msg? result.data.msg : '服务异常啦！')
        return Promise.reject(result.data)
    },
    err=>{
        console.log(err)
        if (err.response.status === 401){
            message.error("请先登录！")
            router.push("/login")
        }else{
            message.error("服务异常啦！")
        }
        return Promise.reject(err);
    }
)

export default instance;